import React, { Component } from "react";
import Test from "./Editor";
import { connect } from "react-redux";
import { setComment } from "../action/counter";
import $ from "jquery";
import { setcookie, getcookie, delcookie } from "./cookie";
class Comments extends Component {
  componentDidMount() {
    var clist = [];
    
    fetch("http://10.31.160.71:3000/comment/lists/"+getcookie("pId"), {
      method: "put"
     
    })
      .then(data => data.json())
      .then(data => {
        var clists = data.rows.reverse()  ;
        let len = clists.length;
        for (let i = 0; i < len; i++) {
          clists[i].date=clists[i].date.slice(0,10);
          clist.push(
            <div key={i} className="list-group-item ">
              <div className="d-flex w-100 justify-content-between">
                <h5 className="mb-1 uname">{clists[i].username}</h5>
                <small>{clists[i].date}</small>
              </div>
              <p className="mb-1" dangerouslySetInnerHTML={{__html:clists[i].text}} />
              <small>---------------------------------------------------------------------------------------------------------------</small>
            </div>
          );
        }
        console.log(clist);
        this.props.setComment(clist);
      });
  }
  pComment() {
    if (getcookie("name") && this.props.pcomments) {
      $.ajax({
        url: "http://10.31.160.71:3000/comment/data",
        method: "post",
        data: {
          text: this.props.pcomments,
          username: getcookie("name"),
          productId: getcookie("pId")
        }
      }).then(function(data) {
        console.log(data);
        location.reload();
      });
    } else {
      alert("请登录or输入内容");
    }
  }
  render() {
    return (
      <div>
        <div className="commentsContent">
          <Test />
          <div className="commentBtn">
            <button
              type="button"
              className="btn btn-success"
              onClick={this.pComment.bind(this)}
            >
              Comment
            </button>
          </div>
          <div className="list-group commentList">
            {this.props.clists}
            <div className="row commentFooter" />
          </div>
        </div>
      </div>
    );
  }
}

// export default Comments;
const mapStateToProps = state => {
  return {
    name: state.name,
    pcomments: state.comments,
    clists: state.clists
  };
};
export default connect(mapStateToProps, { setComment })(Comments);
